package com.fly.hello.web.async;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api(tags = "webAsync异步请求")
@RequestMapping("/async/webAsync")
public class WebAsyncTaskController
{
    @Autowired
    private ThreadPoolTaskExecutor executor;
    
    /**
     * WebAsyncTask升级版callable，增加超时异常等处理
     * 
     * @return
     */
    @GetMapping("/async")
    public WebAsyncTask<String> asyncTask()
    {
        WebAsyncTask<String> webAsyncTask = new WebAsyncTask<String>(1000L, executor, () -> {
            String threadName = Thread.currentThread().getName();
            try
            {
                // 业务逻辑处理
                Long num = RandomUtils.nextLong(500L, 2000L);
                log.info("thread: {}, sleep {} milliseconds", threadName, num);
                TimeUnit.MILLISECONDS.sleep(num);
                return threadName + ", sleep milliseconds: " + num;
            }
            catch (InterruptedException e)
            {
                log.error(e.getMessage(), e);
                return threadName + ", " + e.getMessage();
            }
        });
        webAsyncTask.onCompletion(() -> log.info("调用完成"));
        webAsyncTask.onError(() -> {
            log.error("业务处理出错");
            return "error";
        });
        webAsyncTask.onTimeout(() -> {
            log.info("业务处理超时");
            return "Time Out";
        });
        return webAsyncTask;
    }
}
